# -*- coding: utf-8 -*-
import csv
import sys
import random
import Queue
total=0
parentOut=0
tempQueue=Queue.Queue()
voltageLevel=['500kv','220kv','110kv','35kv','10kv','220v']
def createCsvRoot(reader,writer):
	writer.writerow(['name','in','out'])
	i=0
	for line in reader:
		i+=1
		if not(line[0]=="name"):
			finishALine(line,writer)
			# print line
		# if(i==3):
		# 	return
def finishALine(line,writer):	
	global tempQueue
	name=line[0]
	if(name.split('@')[1]=='0'):#这是根节点
		inVol=random.uniform(100000, 1000000)
		outVol=random.uniform(100000,1000000)
		while outVol>=inVol:
			outVol=random.uniform(100000,1000000)
		writer.writerow([name,inVol,outVol])
		tempQueue.put(outVol)
	children=line[1].split()#自动忽略为空的项
	parentOut=tempQueue.get()
	childNolossIn=float(parentOut)/len(children)
	for child in children:
		writeAlineOfChild(writer,child,childNolossIn)
def isNameTheLastLevel(name):#根据节点名字判断是不是电表节点（根据电压）
	global voltageLevel
	return voltageLevel[len(voltageLevel)-1]==name.split('@')[0]
def writeAlineOfChild(writer,childName,childNolossIn):
	global tempQueue
	global total
	inVol=childNolossIn	
	if(not isNameTheLastLevel(childName)):#不是电表节点
		if random.randint(0,0)==1:#三分之一的几率产生上级到下级的线损
			inVol=inVol*0.8	
		outVol=inVol
		writer.writerow([childName,inVol,outVol])
		total+=1
		tempQueue.put(outVol)
	else:#是电表节点
		writer.writerow([childName,inVol*0.85,'0'])
		total+=1
if __name__ == '__main__':
	print "create in out csv"
	if len(sys.argv)==3:#第一个参数是输入文件，第二个参数是输出文件
		with open(sys.argv[1], 'rb') as csvfile:
			reader = csv.reader(csvfile)
			with open(sys.argv[2],'wb+') as csvfile2:
				writer=csv.writer(csvfile2)
				createCsvRoot(reader,writer)		
				print total
	else:		
		with open('dataForStorm.csv', 'rb') as csvfile:
			reader = csv.reader(csvfile)
			with open('inoutForStorm.csv','wb+') as csvfile2:
				writer=csv.writer(csvfile2)
				createCsvRoot(reader,writer)		
				print total
